//全局音频实例
let audioContext: AudioContext | null = null;
let currentStream ;
//获取音频上下文
const getAudioContext = () => {
  if (!audioContext) {
    audioContext = new AudioContext({ sampleRate: 16000 });
  }
  return audioContext;
}

//获取设备信息
const getMicro = async (index:number = 0) => {
  const devices = await navigator.mediaDevices.enumerateDevices()
   const microphones = devices.filter(d => d.kind === 'audioinput');
  return microphones[index] || null;
}
//获取设备列表
const getAudioDevices = async () => {
  const devices = await navigator.mediaDevices.enumerateDevices()
  return devices
}
//初始化录音
const startRecording = async (deviceId?: string) => {
  try {
    if (currentStream) {
      currentStream.getTracks().forEach(track => track.stop());
    }
     const targetDeviceId = deviceId || (await getMicro())?.deviceId;
    if (!targetDeviceId) throw new Error('No available microphone');

    currentStream = await navigator.mediaDevices.getUserMedia({ audio: { deviceId: { exact: targetDeviceId } , sampleRate: 16000 } }) //获取音频流
    return currentStream
  } catch (error) {
    console.log(error)
      throw error;

  }
}

//停止录音
const stopRecording = () => {
  if (currentStream) {
    currentStream.getTracks().forEach(track => track.stop());
    currentStream = null;
  }
}



export default {
  getAudioContext,
  getMicro,
  getAudioDevices,
  startRecording,
  stopRecording
}
